/****************************************************
          File Name:43-1.c
          Author: Abby Cin
          Mail: abbytsing@gmail.com
          Created Time: Tue 09 Sep 2014 04:18:10 PM CST
*****************************************************/

#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
#include<errno.h>

void err(char *fun)
{
    perror(fun);
    exit(errno);
}

int main(int argc, char *argv[])
{
    int fd[2],status;
    int blocks, block_size;
    if(argc<3)
    {
        printf("%s block_size blocks\n",argv[0]);
        exit(EXIT_FAILURE);
    }

    if(pipe(fd)==-1)
        err("pipe");
    
    block_size=atoi(argv[1]);
    blocks=atoi(argv[2]);
    int  buffer[blocks];
    int  buf[blocks];

    for(int i=0;i<blocks;i++)
        buf[i]=i;

    switch(fork())
    {
        case -1:
            err("fork");
        case 0:
            sleep(1);
            if(close(fd[1])==-1)
                err("close write");
 /*           for(;;)
            {
                status=read(fd[0],buffer,block_size);
                if(status==-1)
                    err("read pipe");
                if(status==0)
                    break;
            }
            */
                status=read(fd[0],buffer,blocks);
                if(status==-1)
            exit(EXIT_SUCCESS);
        default:
            if(close(fd[0])==-1)
                err("close read");
            if(write(fd[1],buf,blocks)==-1)
                err("write pipe");
            printf("writing done\n");
            break;
    }

    sleep(1);
    printf("the max broadwidth of pipe now is: %d\n",blocks); // 1047489
    return 0;
}
